﻿using Ruici.BLL;
using RuiciWebSite.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Ruici.Web.Services.ServiceForWeb;
using RuiciWebSite.Common;

namespace RuiciWebSite.Controllers
{
    public class LoginController : Controller
    {
        public static bool _bLoginSuccess = false;
        UserBll usersSevice = new UserBll();
        RuiciCommoms common = new RuiciCommoms();

        // GET: Login
        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult UserLogin(LoginViewModel user)
        {
            if (user == null)
            {
                return Json(new ReturnCode(-1, "请检查是否填写了您的个人信息"), JsonRequestBehavior.AllowGet);
            }
            //获取登录信息
            Dictionary<int, string> sResultDic = usersSevice.Login(user.UserId, user.Password);

            if (sResultDic.First().Key != 0)
            {
                if (Session["LoginFail"] == null)
                    Session["LoginFail"] = 1;
                else
                    Session["LoginFail"] = int.Parse(Session["LoginFail"].ToString()) + 1;

                if (sResultDic.First().Key == 1)
                    return Json(new ReturnCode(1, sResultDic.First().Value), JsonRequestBehavior.AllowGet);

                if (int.Parse(Session["LoginFail"].ToString()) >= 3)
                    return Json(new ReturnCode(5, sResultDic.First().Value), JsonRequestBehavior.AllowGet);

                return Json(new ReturnCode(-1, sResultDic.First().Value), JsonRequestBehavior.AllowGet);
            }
            else
            {
                Session["LoginFail"] = null;
                //获取网络注册用户
                WebAccount webAccount = usersSevice.getUserExist(user.UserId, user.Password);

                if (webAccount != null)
                {
                    _bLoginSuccess = true;

                    UserInfo userInfo = new UserInfo();

                    userInfo.isLogin = true;
                    userInfo.pid = webAccount.PID;
                    userInfo.userName = webAccount.Name;
                    userInfo.mobile = webAccount.Mobile;

                    Session["isLogin"] = userInfo.isLogin;
                    Session["pid"] = userInfo.pid;
                    Session["userName"] = userInfo.userName;
                    Session["mobile"] = userInfo.mobile;

                    if (user.RememberMe)
                    {
                        common.CreateCookie(Response, userInfo.userName, userInfo.mobile, userInfo.pid);
                    }

                    return Json(userInfo, JsonRequestBehavior.AllowGet);
                }

                return Json(new ReturnCode(-1, "账号与密码不匹配"), JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        /// 获取验证码（注册用户）
        /// </summary>
        /// <param name="regUser"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetValidateCode(RegisterViewModel regUser)
        {
            if (!string.IsNullOrEmpty(regUser.Mobile))
            {
                WebAccount acount = usersSevice.getWebAccountByMobile(regUser.Mobile);
                if (acount == null)
                {
                    common.GenerateValidateCode(Session, regUser.Mobile);
                    usersSevice.SendMessage(regUser.Mobile, Session["ValidationCode"].ToString());
                    return Json(new ReturnCode(1, "验证码已发送，请注意查收!"), JsonRequestBehavior.AllowGet);
                }
                else
                    return Json(new ReturnCode(2, "该手机号已被注册!"), JsonRequestBehavior.AllowGet);
            }
            return Json(new ReturnCode(-1, "获取验证码失败，请重试!"), JsonRequestBehavior.AllowGet);

        }
        /// <summary>
        /// 注册新用户
        /// </summary>
        /// <param name="regUser"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult RegisterNewUser(RegisterViewModel regUser)
        {
            if (regUser == null)
                return Json(new ReturnCode(-1, "请检查是否填写了您的个人信息"), JsonRequestBehavior.AllowGet);

            string sErrorMessage = common.CheckValidateCode(Session, regUser.Mobile, regUser.ValidateCode);

            if (!string.IsNullOrEmpty(sErrorMessage))
                return Json(new ReturnCode(-1, sErrorMessage), JsonRequestBehavior.AllowGet);

            Dictionary<int, string> RegistResultDic = usersSevice.registNewUser(regUser.Mobile, regUser.Password);

            //Dictionary<int,string> RegistResultDic = new Dictionary<int,string>();
            //RegistResultDic.Add(1, "注册成功");

            if (RegistResultDic.First().Key == 1)
            {
                WebAccount webAccount = usersSevice.getUserExist(regUser.Mobile, regUser.Password);
                if (webAccount != null)
                {
                    UserInfo userInfo = new UserInfo();
                    userInfo.isLogin = true;
                    userInfo.pid = webAccount.PID;
                    userInfo.userName = webAccount.Name;
                    userInfo.mobile = webAccount.Mobile;

                    Session["isLogin"] = userInfo.isLogin;
                    Session["pid"] = userInfo.pid;
                    Session["userName"] = string.Empty;
                    Session["mobile"] = userInfo.mobile;
                }
            }
            return Json(new ReturnCode(RegistResultDic.First().Key, RegistResultDic.First().Value), JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult submitExtra(RegisterViewModel regUser)
        {
            bool bUpdateResult = false;
            int sResultCode;
            if (regUser == null)
                return Json(new ReturnCode(-1, "请检查是否填写了您的个人信息。"), JsonRequestBehavior.AllowGet);

            bUpdateResult = usersSevice.updateUser(regUser.Name, regUser.CertCode, int.Parse(Session["pid"].ToString()), regUser.Gender);

            if (bUpdateResult)
            {
                sResultCode = 1;
                Session["userName"] = regUser.Name;
            }
            else
                sResultCode = -1;

            return Json(new ReturnCode(sResultCode, bUpdateResult.ToString()), JsonRequestBehavior.AllowGet);
        }
    }

    public class ReturnCode
    {
        public ReturnCode(int code, string msg)
        {
            this.Code = code;
            this.Msg = msg;
        }
        public int Code { get; set; }
        public string Msg { get; set; }
    }

    public class UserInfo
    {
        public bool isLogin { get; set; }
        public int pid { get; set; }
        public string userName { get; set; }
        public string mobile { get; set; }
    }
}